package com.example.educational.controller;

import cn.hutool.core.util.ObjectUtil;
import com.example.educational.controller.utils.Code;
import com.example.educational.controller.utils.Result;
import com.example.educational.entity.NoticeReceived;
import com.example.educational.entity.User;
import com.example.educational.entity.VerCode.AesException;
import com.example.educational.service.CorporateService;
import com.example.educational.service.NoticeReceivedService;
import com.example.educational.service.ReadPeopleService;
import com.example.educational.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 完成企业内部应用的业务逻辑
 */
@Slf4j
@RestController
@RequestMapping("/innAppService")
public class InnerAppController {

    @Autowired
    UserService userService;

    @Autowired
    CorporateService corporateService;

    @Autowired
    NoticeReceivedService noticeReceivedService;

    @Autowired
    ReadPeopleService readPeopleService;

    /**
     * 验证企业微信的回调服务
     */
    @ApiOperation(value = "验证企业微信内部应用的回调服务")
    @GetMapping("/callback")
    private String affirmFromWorkChart(@RequestParam("msg_signature") String sVerifyMsgSig, @RequestParam("timestamp") String sVerifyTimeStamp, @RequestParam("nonce") String sVerifyNonce, @RequestParam("echostr") String sVerifyEchoStr) throws AesException {
        // 1.验证企业信息回调
        String sEchoStr = corporateService.verifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr);
        // 2.打印输出
        log.info("验证成功~: " + sEchoStr);
        return sEchoStr;
    }

    /**
     * 完成企业微信的回调服务
     */
    @ApiOperation(value = "完成企业微信内部应用的回调服务")
    @PostMapping("/callback")
    private String callbackFromWorkChart(@RequestParam("msg_signature") String sReqMsgSig, @RequestParam("timestamp") String sReqTimeStamp, @RequestParam("nonce") String sReqNonce, @RequestBody String sReqData) throws AesException {
        // 1.回复企业微信验证
        return corporateService.reqMsgURL(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData);
    }

    @ApiOperation(value = "获取通知详细信息")
    @PostMapping("/gainImgSrc")
    private Result getImgSrc(@RequestParam("taskId") String taskId, HttpServletRequest request) {
        // 1. 获取用户信息
        User user = (User) request.getAttribute("user");
        String userId = user.getId();
        log.info("已获取用户信息~:" + userId);
        // 2. 添加已读人员信息
        Boolean result = userService.recordReadUser(userId, taskId);
        log.info("该用户信息已记录");
        // 3. 获取通知信息
        NoticeReceived noticeReceived = noticeReceivedService.getReceiveNoticed(taskId);
        log.info("已获取通知信息");
        if (ObjectUtil.isNotNull(noticeReceived)) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("noticeReceivedSrc", noticeReceived.getImgSrc());
            return new Result(Code.success, resultMap, "获取成功~");
        } else {
            return new Result(Code.err, null, "该通知不存在~");
        }
    }

    @ApiOperation(value = "获取已读人员信息")
    @GetMapping("/gainReadPeople")
    private Result getReadPeople(@RequestParam("taskId") String taskId, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        // 1. 获取用户信息
        User user = (User) request.getAttribute("user");
        log.info("已获取用户信息~:" + user.getId());

        // 2. 获取已读人员
        String name = "";
        ArrayList<User> userArrayList = userService.getUsersRead(taskId, name);
        log.info("已获取已读人员信息");
        if (userArrayList.size() != 0) {
            resultMap.put("readPeople", userArrayList);
            resultMap.put("totalCount", userArrayList.size());
            resultMap.put("user", user);
            return new Result(Code.success, resultMap, "获取成功~");
        } else {
            resultMap.put("user", user);
            return new Result(Code.err, resultMap, "该通知无人读取~");
        }
    }

    @ApiOperation(value = "获取未读人员信息")
    @GetMapping("/gainUnReadPeople")
    private Result getUnReadPeople(@RequestParam String taskId, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        // 1. 获取用户信息
        User user = (User) request.getAttribute("user");
        log.info("已获取用户信息~:" + user.getId());
  

        // 2. 获取未读人员
        String name = "";
        ArrayList<User> userArrayList = userService.getUsersUnRead(taskId, name);
        log.info("已获取未读人员信息");
        if (userArrayList.size() != 0) {
            resultMap.put("user", user);
            resultMap.put("unReadPeople", userArrayList);
            resultMap.put("totalCount", userArrayList.size());
            return new Result(Code.success, resultMap, "获取成功~");
        } else {
            resultMap.put("user", user);
            return new Result(Code.err, resultMap, "该通知所有人已读取~");
        }
    }

    @ApiOperation(value = "搜索已读人员信息")
    @GetMapping("/searchReadPeople")
    private Result searchReadPeople(@RequestParam("taskId") String taskId, @RequestParam(value = "name", required = false) String name, @RequestParam String userId) {
        Map<String, Object> resultMap = new HashMap<>();
        // 1.验证用户身份
        User user = userService.checkUserIdentify(userId);
        if (ObjectUtil.isNull(user)) {
            return new Result(Code.err, resultMap, "用户验证失败！");
        }
        // 2. 获取已读人员
        ArrayList<User> userArrayList = userService.getUsersRead(taskId, name);
        if (userArrayList.size() != 0) {
            resultMap.put("readPeople", userArrayList);
            resultMap.put("totalCount", userArrayList.size());
            return new Result(Code.success, resultMap, "查询成功~");
        } else {
            return new Result(Code.err, resultMap, "无此姓名！");
        }
    }

    @ApiOperation(value = "搜索未读人员信息")
    @GetMapping("/searchUnReadPeople")
    private Result searchUnReadPeople(@RequestParam String taskId, @RequestParam(value = "name", required = false) String name, @RequestParam String userId) {
        Map<String, Object> resultMap = new HashMap<>();
        // 1.验证用户身份
        User user = userService.checkUserIdentify(userId);
        if (ObjectUtil.isNull(user)) {
            return new Result(Code.err, resultMap, "用户验证失败！");
        }
        // 2. 获取未读人员
        ArrayList<User> userArrayList = userService.getUsersUnRead(taskId, name);
        if (userArrayList.size() != 0) {
            resultMap.put("unReadPeople", userArrayList);
            resultMap.put("totalCount", userArrayList.size());
            return new Result(Code.success, resultMap, "查询成功~");
        } else {
            return new Result(Code.err, resultMap, "无此姓名！");
        }
    }


    @ApiOperation(value = "通知一下")
    @PostMapping("/dingUsers")
    private Result dingUsers(@RequestParam String userNameList, @RequestParam String taskId, @RequestParam String userId) {

        // 1.验证用户身份
        User user = userService.checkUserIdentify(userId);
        log.info("已获取用户信息~:" + user.getId());

        if (user.getRole() < 0) {
            return new Result(Code.err, null, "该用户无权限！！！");
        }
        // 2.获取通知信息
        NoticeReceived noticeReceived = noticeReceivedService.getReceiveNoticed(taskId);
        if (ObjectUtil.isNull(noticeReceived)) {
            return new Result(Code.err, null, "该通知不存在！！！");
        }
        // 3.获取所有用户Id列表
        ArrayList<String> userIdList = userService.changeIdFromName(userNameList);
        if (ObjectUtil.isEmpty(userIdList)) {
            return new Result(Code.err, null, "该通知不存在未查看用户~");
        }
        // 4.通知推送
        Boolean result = corporateService.pushNotice2User(noticeReceived, userIdList);
        if (result) {
            log.info("通知已提醒");
            return new Result(Code.success, null, "通知提醒成功~");
        } else {
            return new Result(Code.err, null, "通知提醒失败！！！");
        }

    }

}
